from datetime import datetime
from typing import Union

from apscheduler.schedulers.asyncio import AsyncIOScheduler
from fastapi import FastAPI

# TODO 运行项目
# TODO 命令：uvicorn main:app --reload
app = FastAPI()

# 定时任务，创建一个scheduler实例
scheduler = AsyncIOScheduler()


# 使用cron表达式，每分钟执行
@scheduler.scheduled_job('interval', minutes=1)
async def do_task():
    # 执行任务的内容，例如打印当前时间
    print(f"1 minutes crontab: The current time is {datetime.now()}")

# 使用cron表达式，每2秒执行
@scheduler.scheduled_job('interval', seconds=2)
async def do_task():
    # 执行任务的内容，例如打印当前时间
    print(f"1 seconds crontab: The current time is {datetime.now()}")


# 启动服务时，启动scheduler
@app.on_event("startup")
async def startup_event():
    print("FastApi服务启动")
    # 启动定时任务
    scheduler.start()
    print("定时任务启动啦~")


# 关闭服务时，关闭scheduler
@app.on_event("shutdown")
async def shutdown_event():
    print("FastApi服务关闭")
    scheduler.shutdown()
    print("定时任务关闭啦~")


@app.get("/")
def read_root():
    return {"Hello": "World"}


# http://localhost:8000/items/1?q=helloworld
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Union[str, None] = None):
    return {"item_id": item_id, "q": q}
